<template>
  <div>
    <!-- 公司資料卡片 -->
    <el-card class="box-card" style="min-height: 500px">
      <template #header>
        <div class="card-header">
          <span>{{ $t('router.companyData') }}</span>
          <span v-if="platformUser" style="color: red"
            >&nbsp;&nbsp;&nbsp;&nbsp;{{ $t('company.onlyTenant') }}</span
          >
        </div>
      </template>
      <el-form
        :model="compView"
        :rules="compRule"
        ref="compRef"
        label-position="left"
        label-width="150px"
        style="padding-top: 10px; padding-right: 40px"
        :disabled="compDisabled"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('company.nameCn')" prop="name" class="requireLabel">
              <el-input
                class="required_input"
                v-model="compView.name"
                :placeholder="$t('company.inputNameChi')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('company.licenseNo')" prop="licenseNo" class="requireLabel">
              <el-input
                class="required_input"
                v-model="compView.licenseNo"
                :placeholder="$t('company.licenseNo')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('company.phone')" class="normal_label" prop="telNo">
              <el-input
                v-model="compView.telNo"
                :placeholder="$t('company.iptPhone')"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('company.webSite')" prop="webSite" class="normal_label">
              <el-input
                v-model="compView.webSite"
                :placeholder="$t('company.webSite')"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            <el-form-item label="Email" prop="email" style="width: 100%" class="normal_label">
              <el-input
                v-model="compView.email"
                placeholder="Email"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('company.nameEN')" prop="enName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="compView.enName"
                :placeholder="$t('company.inputNameEn')"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.companyNameAddressCn')"
              prop="address"
              class="requireLabel"
            >
              <el-input
                class="required_input"
                v-model="compView.address"
                :placeholder="$t('company.addresInfoCn')"
                type="textarea"
                :autosize="{ minRows: 2 }"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.companyNameAddressEn')"
              prop="enAddr"
              class="requireLabel"
            >
              <el-input
                class="required_input"
                v-model="compView.enAddr"
                :placeholder="$t('company.iptAddressEn')"
                type="textarea"
                :autosize="{ minRows: 2 }"
                maxlength="255"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('company.uploadLogo')"
              label-width="138px"
              class="normal_label"
            >
              <div class="uploadFileDiv" style="margin-left: 12px">
                <el-upload
                  v-model:file-list="companyLogoUrl"
                  :action="uploadUrl"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-success="handleAvatarSuccess"
                  class="avatar-uploader"
                  :headers="headers"
                  :limit="1"
                  :on-remove="handleRemove"
                  :on-change="handleChange"
                  :class="{ hide: hideUploadCard }"
                  accept=".jpeg,.png,.jpg,.bmp,.gif"
                  :disabled="compDisabled"
                >
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible" width="350px" draggable>
                  <el-image :src="dialogImageUrl" style="display: block; margin: 0 auto" />
                </el-dialog>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row class="top_button" v-show="!platformUser">
        <el-col v-if="!compDisabled">
          <el-button type="primary" plain @click="saveCompany">
            <el-icon><Select /></el-icon>&nbsp;{{ $t('common.save') }}
          </el-button>
          <el-button type="info" plain @click="giveUp" style="margin-left: 30px">
            <el-icon> <Close /> </el-icon>&nbsp;{{ $t('common.giveUp') }}
          </el-button>
        </el-col>
        <el-col v-else>
          <el-button
            v-if="hasAuth('edit')"
            type="primary"
            plain
            @click="compDisabled = !compDisabled"
          >
            <el-icon> <Edit /> </el-icon>&nbsp;{{ $t('common.modify') }}
          </el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts">
import { onActivated, onMounted, reactive, toRefs, ref } from 'vue'
import { Plus, Edit, Select, Close } from '@element-plus/icons-vue'
import { updateCompany } from '@/api/company'
import { getCurUser, getToken } from '@/utils'
import { PATH_URL } from '@/config/axios'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { getUserPageAuth } from '@/api/system/authority'
import { hasElementAuth } from '@/utils/authority'
import type { UploadProps } from 'element-plus'
import { getFileUrl } from '@/api/file/index'
import { useI18n } from '@/hooks/web/useI18n'
import { useCache } from '@/hooks/web/useCache'
export default {
  name: 'CompanyData',
  components: { Plus, Edit, Select, Close },
  props: {},
  setup() {
    const compRef = ref()
    const { emitter } = useEmitt()
    const router = useRouter()
    const { wsCache } = useCache()
    const { t } = useI18n()
    const state = reactive({
      // 公司資料
      compView: {
        url: '',
        seq: ''
      },
      compRule: {
        name: {
          required: true,
          message: t('company.errNameCnEmpty'),
          trigger: ['blur', 'change']
        },
        enName: [
          { required: true, message: t('company.errNameEnEmpty'), trigger: ['blur', 'change'] },
          {
            pattern: /^[^\u4e00-\u9fa5]+$/,
            message: t('common.errNotCN'),
            trigger: ['blur', 'change']
          }
        ],
        licenseNo: {
          required: true,
          message: t('company.inputOrderNo'),
          trigger: ['blur', 'change']
        },
        telNo: [
          {
            pattern: /^(\(){0,1}(\+){0,1}[\d\-( )]+$/,
            message: t('company.errMobileOrTelNo'),
            trigger: ['blur', 'change']
          },
          {
            pattern: '[^ \x22]+',
            message: t('company.emptyMsg'),
            trigger: ['blur', 'change']
          }
        ],
        email: {
          pattern: /^[^@]+[@]{1}[^@]+$/,
          message: 'Email' + t('company.errFormat'),
          trigger: 'blur'
        },
        enAddr: {
          pattern: /^[^\u4e00-\u9fa5]+$/,
          message: t('common.errNotCN'),
          trigger: ['blur', 'change']
        }
      },
      compDisabled: true,
      companyLogo: [{}],
      companyLogoUrl: [{}],
      uploadUrl: PATH_URL + 'form/file/upload',
      hideUploadCard: false,
      dialogVisible: false,
      dialogImageUrl: '',
      pageAuths: [{}],
      platformUser: false
    })
    const handleAvatarSuccess = (res) => {
      if (res.success == true) {
      } else {
      }
    }
    const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
      state.dialogImageUrl = uploadFile.url!
      state.dialogVisible = true
    }
    onMounted(async () => {
      state.platformUser = getCurUser().platformUser
      methods.getCompanyData()
      init()
    })
    onActivated(async () => {})
    const methods = {
      // 是否有权限
      hasAuth(key) {
        return hasElementAuth(state.pageAuths, key)
      },
      // 保存公司
      saveCompany() {
        compRef.value.validate(async (vaild) => {
          if (vaild) {
            const company = wsCache.get('companyData')
            let params = Object.assign({}, state.compView)
            params.seq = company.data.seq
            params.url = ''
            if (state.companyLogo.length > 0) {
              let url = {
                fileId: state.companyLogo[0].pkId,
                createBy: state.companyLogo[0].remark
              }
              params.url = JSON.stringify(url)
            }
            if (params.url.length == 0 || params.url == '{}') {
            }
            await updateCompany(params).then((res) => {
              if (res) {
                init()

                emitter.emit('updateCompanyData')
                emitter.emit('refreshLogo')
              }
            })
            state.compDisabled = true
          }
        })
      },
      // 獲取logo
      getLogoUrl(item): string {
        let fileJosn = state.companyLogo[item] as any
        let id = fileJosn.fileId
        if (!id) {
          return ''
        }
        let url = getFileUrl(id)
        return url
      },
      handleRemove(file, fileList) {
        if (!fileList) return
        methods.addFile(fileList)
        state.hideUploadCard = fileList.length >= 1
      },
      handleChange(file, fileList) {
        if (!fileList) return
        methods.addFile(fileList)
        state.hideUploadCard = fileList.length >= 1
      },
      addFile(fileList) {
        if (!fileList) return
        state.companyLogo = []
        for (let item of fileList) {
          if (item.response) state.companyLogo.push(item.response.data[0])
        }
      },
      // 放棄
      giveUp() {
        compRef.value?.clearValidate()
        state.compDisabled = true
        methods.getCompanyData()
      },
      async getCompanyData() {
        const company = wsCache.get('companyData')
        if (!company || !company.data) {
          return
        }
        state.compView = company.data
        state.companyLogo = []
        state.companyLogoUrl = []

        if (company.data.url != '') {
          const urlObj = JSON.parse(company.data.url)
          if (urlObj.fileId) {
            urlObj.pkId = urlObj.fileId
          }
          state.companyLogo.push(urlObj)
          if (state.companyLogo) {
            for (let i = 0; i < state.companyLogo.length; i++) {
              state.companyLogoUrl.push({
                url: methods.getLogoUrl(i)
              })
            }
            if (state.companyLogoUrl.length >= 1) state.hideUploadCard = true
          }
        }
      }
    }
    //渲染页面的接口
    const init = async () => {
      // 查詢地區
      let muid = router.currentRoute.value.meta.id as string
      state.pageAuths = (await getUserPageAuth(muid)).data
    }
    return {
      ...toRefs(state),
      compRef,
      ...methods,
      handleAvatarSuccess,
      handlePictureCardPreview
    }
  },
  computed: {
    headers() {
      let token = getToken()
      if (token) {
        return { Authorization: token }
      }
      return {}
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  .card-header {
    font-size: 16px;
    letter-spacing: 1px;
  }

  .avatar-uploader {
    width: 120px;
    height: 120px;
    display: block;

    // border: 1px dashed #cdd0d4;
    .el-icon.avatar-uploader-icon {
      width: 118px;
      height: 118px;
      font-size: 25px;
      text-align: center;
      color: #8c939d;
    }

    :deep(.el-upload--picture-card) {
      --el-upload-picture-card-size: 118px;
    }

    :deep(.el-upload-list__item) {
      width: 118px;
      height: 118px;
    }
  }

  :deep(.hide .el-upload--picture-card) {
    display: none;
  }
}

.normal_label,
.required_input {
  position: relative;
  left: 10px;
}

:deep(.normal_label .el-form-item__error) {
  left: 0px;
}

:deep(.requireLabel .el-form-item__error) {
  margin-left: 10px;
}

// 摺叠面板
.el-collapse {
  border-color: transparent;

  :deep(.el-collapse-item__wrap) {
    border-bottom: none;
    border-top: 1px solid var(--el-collapse-border-color);
  }

  .collapse-card {
    margin: 10px 0;

    :deep(.el-collapse-item__header) {
      padding-right: 0;
      font-size: 16px;
      border-color: transparent;
    }
  }
}

:deep(.el-input) {
  font-size: 12px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-cascader) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  height: 80px;
  font-size: 12px;
}

.top_button {
  text-align: center;
  margin: 10px 0;
}

// 查詢狀態下一般input輸入框已填信息變黑色展示
:deep(.el-input.is-disabled .el-input__inner) {
  color: #000000;
}

// 查詢狀態下textarea輸入框已填信息變黑色展示
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  color: #000000;
}

// 查詢狀態下radio單選框已填信息變黑色展示
:deep(.el-radio__input.is-disabled.is-checked .el-radio__inner) {
  color: #000000;
}

:deep(.el-radio__input.is-disabled + span.el-radio__label) {
  color: #000000;
}

// 查詢狀態下checkbox複選框已填信息變黑色展示
:deep(.el-checkbox__input.is-disabled .el-checkbox__inner) {
  color: #000000;
}

:deep(.el-checkbox__input.is-disabled + span.el-checkbox__label) {
  color: #000000;
}

// 查詢狀態下一般input輸入框placeholder隱藏
:deep(.el-input.is-disabled .el-input__inner) {
  &::placeholder {
    color: transparent;
  }
}

// 查詢狀態下textarea輸入框placeholder隱藏
:deep(.el-textarea.is-disabled .el-textarea__inner) {
  &::placeholder {
    color: transparent;
  }
}
</style>
